package sqlanalysisgui.view.model.sorter;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;

import sqlanalysisgui.view.model.TableInfo;

public class SearchTableViewSorter extends ViewerSorter {
	  private static final int ASCENDING = 0;

	  private static final int DESCENDING = 1;
	  
	  public static final int COLUMN_TABLE = 0;
	  public static final int COLUMN_CRUD = 1;
	  public static final int COLUMN_SOURCE_LINE = 2;
	  public static final int COLUMN_FILE_NAME = 3;
	  public static final int COLUMN_FILE_PATH = 4;

	  private int column;

	  private int direction;

	  /**
	   * Does the sort. If it's a different column from the previous sort, do an
	   * ascending sort. If it's the same column as the last sort, toggle the sort
	   * direction.
	   * 
	   * @param column
	   */
	  public void doSort(int column) {
	    if (column == this.column) {
	      // Same column as last sort; toggle the direction
	      direction = 1 - direction;
	    } else {
	      // New column; do an ascending sort
	      this.column = column;
	      direction = ASCENDING;
	    }
	  }

	  /**
	   * Compares the object for sorting
	   */
	  public int compare(Viewer viewer, Object e1, Object e2) {
	    int rc = 0;
	    TableInfo p1 = (TableInfo) e1;
	    TableInfo p2 = (TableInfo) e2;

	    // Determine which column and do the appropriate sort
	    switch (column) {
	    case COLUMN_TABLE:
	      rc = collator.compare(p1.getTableName(), p2.getTableName());
	      break;
	    case COLUMN_CRUD:
	      rc = collator.compare(p1.getCrudType(), p2.getCrudType());
	      break;
	    case COLUMN_SOURCE_LINE:
	      rc = p1.getSourceLineInteger() > p2.getSourceLineInteger() ? 1 : -1; //collator.compare(p1.getSourceLine(), p2.getSourceLine());
	      break;
	    case COLUMN_FILE_NAME:
	    	rc = collator.compare(p1.getFileName(), p2.getFileName());
	    	break;
	    case COLUMN_FILE_PATH:
	    	rc = collator.compare(p1.getSourcePath(), p2.getSourcePath());
	    	break;
	    }
//p1.getProjectPath() > p2.getProjectPath() ? 1 : -1;
	    // If descending order, flip the direction
	    if (direction == DESCENDING)
	      rc = -rc;

	    return rc;
	  }
}
